//
//  CachedDownloadManager.m
//  CommunityNannyO2O
//
//  Created by 90 on 15/7/21.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "CachedDownloadManager.h"

@interface CachedDownloadManager()
{

}

@end


@implementation CachedDownloadManager

-(NSString *)getDocumentsPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //获取路径
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];

    return documentsDirectory;
}

- (NSString *)makeDiskCachePath:(NSString*)fullNamespace
{
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    
    NSString* path = [self getDocumentsPath];
    
    return [path stringByAppendingPathComponent:fullNamespace];
}

- (NSMutableDictionary *)getCacheDictionary:(NSString *)fileName
{
    self.cacheDictionaryPath = [self makeDiskCachePath:fileName];
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    //判断是否存在缓存字典的数据
    if ([fileManager
         fileExistsAtPath:self.cacheDictionaryPath] == YES)
    {
        //加载缓存字典中的数据
        NSMutableDictionary *dictionary =
        [[NSMutableDictionary alloc]
         initWithContentsOfFile:self.cacheDictionaryPath];
        
        //移除没有下载完成的缓存数据
//        [self removeCorruptedCachedItems];
        
        return dictionary;
    }
    else
    {
        //创建一个新的缓存字典
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        
        return dictionary;
    }
}

/* 保持缓存字典 */
- (BOOL) saveCacheDictionary
{
    if (self.cacheDictionary && self.cacheDictionaryPath.length)
    {
        return [self.cacheDictionary writeToFile:self.cacheDictionaryPath atomically:YES];
    }
    return NO;
}

/* 公有方法：下载 */
- (BOOL) download:(NSString *)paramURLAsString
urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds
updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache
{
    self.cacheDictionary = [self getCacheDictionary:@"CachedDownloads.dic"];
    
    if (self.cacheDictionary == nil
        ||[paramURLAsString length] == 0)
    {
        return NO;
    }
    
    BOOL result = NO;
    
    paramURLAsString = [paramURLAsString lowercaseString];
    
    //根据url，从字典中获取缓存项的相关数据
    NSMutableDictionary *itemDictionary = [self.cacheDictionary objectForKey:paramURLAsString];
    
    /* 使用下面这些变量帮助我们理解缓存逻辑 */
    
    //文件是否已经被缓存
    BOOL fileHasBeenCached = NO;
    
    //缓存是否过期
    BOOL cachedFileHasExpired = NO;
    //缓存文件是否存在
    BOOL cachedFileExists = NO;
    //缓存文件能否被加载
    BOOL cachedFileDataCanBeLoaded = NO;
    //缓存文件数据
    NSData *cachedFileData = nil;
    
    NSString *localURL;
    
    if (itemDictionary != nil)
    {
        fileHasBeenCached = YES;
    }
    
    //如果文件已经被缓存，则从缓存项相关数据中获取相关的值
    if (fileHasBeenCached == YES)
    {
        //本地缓存路径
        localURL = [itemDictionary objectForKey:CachedKeyLocalURL];
        
        BOOL isHasCacheData = NO;
        if (cachedFileHasExpired == NO)
        {
            /* 如果缓存文件没有过期，加载缓存文件，并且更新过期时间 */
            NSFileManager *fileManager = [[NSFileManager alloc] init];
            
            if ([fileManager fileExistsAtPath:localURL] == YES)
            {
                cachedFileExists = YES;
                cachedFileData = [NSData dataWithContentsOfFile:localURL];
                if (cachedFileData != nil)
                {
                    isHasCacheData = YES;
                    cachedFileDataCanBeLoaded = YES;
                }
                else
                {
                    isHasCacheData = NO;
                }
            }
            else
            {
                isHasCacheData = NO;
            }
            
            if (isHasCacheData == NO)
            {
                //获取缓存失败
                [self.cacheDictionary removeObjectForKey:paramURLAsString];
                [self saveCacheDictionary];
            }
        }
//                NSLog(@"文件有缓存而且没有过期.");
//                
//                [self.delegate
//                 cachedDownloadManagerSucceeded:self
//                 remoteURL:[NSURL URLWithString:paramURLAsString]
//                 localURL:[NSURL URLWithString:localURL]
//                 aboutToBeReleasedData:cachedFileData
//                 isCachedData:YES];
//                
//                return(YES);
    }
    else    //文件未缓存
    {
        //路径存储到字典
        localURL = [self getCacheDataSavePath:paramURLAsString];
        
        NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] init];
        
        [newDictionary setObject:localURL
                          forKey:CachedKeyLocalURL];
        
        [self.cacheDictionary setObject:newDictionary
                                 forKey:paramURLAsString];
        
        [self saveCacheDictionary];
        
        //下载文件
    }
    
    return YES;
}

-(NSString *)getCacheDataSavePath:(NSString *)paramURLAsString
{
    NSString *localURL = [paramURLAsString
               stringByAddingPercentEscapesUsingEncoding:
               NSUTF8StringEncoding];
    
    localURL = [localURL stringByReplacingOccurrencesOfString:@"://"
                                                   withString:@""];
    
    NSString *documentsDirectory = [self getDocumentsPath];
    
    NSString *path = [documentsDirectory
                stringByAppendingPathComponent:@"/map3Chace"];
    
    path = [path stringByAppendingPathComponent:localURL];
    
    return path;
}


@end




























